import React from 'react';
import { NavLink, Link } from 'react-router-dom';
import md5 from 'md5';
import { Form, Input, Button, Row, Col, Checkbox, message, Icon } from 'antd';
import { getStuRegValidCode, studentRegistry } from '../api';
import http from 'libs/http';
import { _alert, formatDate } from 'libs/utils';
import ImageCodeModal from '../components/ImageCodeModal';
import AgreementModal from '../components/AgreementModal';

const FormItem = Form.Item;

class Login extends React.Component {
  render() {
    return <div>该手机号已经注册，请前去<NavLink to="/student/password_login">登录</NavLink></div>;
  }
}

class StudentRegister extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      validCodeImg: '',
      seconds: '获取验证码',
      mobilePhoneValidCodeFlag: true,
      birthday: '',
      agreement: false,
      dialogIsShow: false,
      confirmDirty: false,
      showImageCodeModal: false,
      showAgreementModal: false,
      mobilePhone: null
    };
  }

  componentDidMount() {
    this.getStuRegValidCode();
  }

  // 获取图片验证码
  getStuRegValidCode = () => {
    getStuRegValidCode((res) => {
      this.setState({
        validCodeImg: res.data,
      });
    });
  }

  // 自定义手机号校验
  validatePhone = (rule, value, callback) => {
    const seconds = this.state.seconds;
    if (value && /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/.test(value)) {
      http.get('/student/common/validMobile', { mobile: value })
      .then(res => {
        if (!res.data) {
          this.setState({
            mobilePhoneValidCodeFlag: typeof seconds !== 'string',
          });
          callback();
        } else {
          callback(<Login />);
        }
      });
    } else {
      this.setState({
        mobilePhoneValidCodeFlag: true,
      });
      callback('请输入正确的11位手机号');
    }
  }
  validateRecommendPhone = (rule, value, callback) => {
    if (value && !/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/.test(value)) {
      callback('请输入正确的11位手机号');
    } else {
      callback();
    }
  }
  handleDialogClose = () => {
    this.setState({
      dialogIsShow: false,
    });
  }

  // 注册
  handleSubmit = (e) => {
    e.preventDefault();
    const form = this.props.form;
    form.validateFields((err, values) => {
      if (!err) {
        const {
          mobilePhone, mobilePhoneCode, password, recommendPhone,
        } = values;
        const postData = {
          mobilePhone, 
          mobilePhoneCode, 
          password: md5(password), 
          recommendPhone,
        };
        !recommendPhone && delete postData.recommendPhone;
        studentRegistry(postData, () => {
          this.props.history.push('/student_center');
          form.resetFields();
        }, (err) => {
          if(err.code == 2){
            form.setFields({
              mobilePhoneCode: {
                value: '',
                errors: [new Error(err.msg)],
              }
            })
          }
          this.getStuRegValidCode();
        });
      }
    });
  }
  // 点击获取手机验证码
  clickMobilePhoneValidCode = () => {
    const { form } = this.props;
    const mobilePhone = form.getFieldValue('mobilePhone');
    this.setState({
      showImageCodeModal: true,
      mobilePhone
    })
  }
  // 图片验证码正确
  handleConfirmImageCode = () => {
    this.setState({
      showImageCodeModal: false
    }, this.startCountDown)
  }
  // 开启倒计时
  startCountDown = () => {
    const form = this.props.form;
    const mobilePhone = form.getFieldValue('mobilePhone');
    let timer = null;
    this.setState({
      seconds: 120,
      mobilePhoneValidCodeFlag: true,
    }, () => {
      timer = setInterval(() => {
        if (this.state.seconds === 0) {
          this.setState({
            seconds: '重新获取',
            mobilePhoneValidCodeFlag: false,
          });
          clearInterval(timer);
          timer = null;
          return;
        }
        this.setState(prevState => ({ seconds: prevState.seconds - 1 }));
      }, 1000);
    });
  }
  agreeTerms = (e) => {
    this.setState({
      agreement: e.target.checked,
    });
  }
  imageCodeClose = () => {
    this.setState({
      showImageCodeModal: false
    })
  }
  // 点击用户协议
  handleClickAgreement = (e) => {
    e.preventDefault();
    this.setState({
      showAgreementModal: true
    })
  }
  // 关闭协议弹窗
  handleAgreementCancel = () => {
    this.setState({
      showAgreementModal: false
    })
  }
  render() {
    const {
      validCodeImg, mobilePhoneValidCodeFlag, seconds, dialogIsShow, showImageCodeModal, showAgreementModal, mobilePhone
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="student-form">
        <Link to="/home" className="close"></Link>
        <h2 className="title">注册</h2>
        <Form onSubmit={this.handleSubmit} onKeyDown={(e) => { if (e.keyCode == 13) { e.preventDefault(); } }}>
          
          
          <div className="valid-code-container">
            <FormItem style={{ marginBottom: 0, height: 64 }}>
              <Row gutter={16}>
                <Col span={16}>
                  {getFieldDecorator('mobilePhoneCode', {
                    rules: [
                      { required: true, message: '手机验证码不能为空' },
                    ],
                  })(<p><Input 
                    size="large"
                    prefix={<Icon type="safety" style={{ color: '#bbb', fontSize: 18 }} />}
                    placeholder="请输入6位手机验证码" autoComplete="off" /></p>)}
                </Col>
                <Col span={6}>
                  <Button
                    style={{ width: 100, height: 40, borderRadius: 2 }}
                    type="primary"
                    disabled={mobilePhoneValidCodeFlag}
                    onClick={this.clickMobilePhoneValidCode}
                  >{seconds}
                  </Button>
                </Col>
              </Row>
            </FormItem>
          </div>
          <div className="mobile-phone-container">
            <FormItem style={{ marginBottom: 0, height: 64 }}>
              {getFieldDecorator('mobilePhone', {
                rules: [
                  { required: true, message: '手机号不能为空' },
                  { validator: this.validatePhone },
                ],
              })(<p><Input 
                size="large"
                placeholder="请输入11位有效手机号码" 
                autoComplete="off" 
                prefix={<Icon type="mobile" style={{ color: '#bbb', fontSize: 18 }} />}
              /></p>)}
            </FormItem>
          </div>
          
          <FormItem style={{ marginBottom: 0, height: 64 }}>
            {getFieldDecorator('password', {
              rules: [
                { required: true, message: '密码不能为空' },
                { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,30}$/, message: '密码应为6-30位数字字母组合' }
              ],
            })(<p><Input.Password 
              size="large"
              placeholder="请输入密码" 
              autoComplete="off" 
              prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
            /></p>)}
          </FormItem>
          <FormItem style={{ marginBottom: 0, height: 64 }}>
            {getFieldDecorator('recommendPhone', {
              rules: [
                { validator: this.validateRecommendPhone },
              ],
            })(<p><Input 
                size="large"
                prefix={<Icon type="mobile" style={{ color: '#bbb', fontSize: 18 }} />}
                placeholder="请输入推荐人手机号码" autoComplete="off" /></p>)}
          </FormItem>
          <div className="agreement-container">
            <FormItem style={{ marginBottom: 30, height: 24 }}>
              {getFieldDecorator('agreement', {
                rules: [
                  { required: true, message: '请阅读并同意此条款' },
                  { pattern: /true/, message: '请阅读并同意此条款'}
                ],
              })(<Checkbox
                style={{
                  width: 340, fontSize: 10, left: 0, bottom: '10px',
                }}
              >申请即视为默认同意用户服务条款。<span style={{ color: '#4285f4' }} onClick={(e) => { this.handleClickAgreement(e) }}>《用户服务条款》</span>
              </Checkbox>)}
            </FormItem>
          </div>
          <Button type="primary" className="btn" htmlType="submit">注册</Button>
          <span className="link-to">
            <span>已有账号？</span>
            <NavLink to="/student/password_login">请登录</NavLink>
          </span>
        </Form>
        {
          showImageCodeModal ? <ImageCodeModal mobilePhone={mobilePhone} handleCloseModal={this.imageCodeClose} handleConfirm={this.handleConfirmImageCode}/> : null
        }
        {
          showImageCodeModal ? <div className="mask"></div> : null
        }
        {
          showAgreementModal ? <AgreementModal onCancel={this.handleAgreementCancel}/> : null
        }
      </div>
    );
  }
}

const WrapStudentLogin = Form.create()(StudentRegister);

export default WrapStudentLogin
